<template>
  <a-modal
    title="文章设置"
    :width="640"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-item
        v-show="false"
        label="id"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input
          v-decorator="['id']"
          :disabled="editable || showable"
        />
      </a-form-item>
      <a-form :form="form">
        <a-form-item
          label="主键"
          :hidden="true"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            :disabled="showable"
            v-decorator="['id', {rules: [{required: false, message: '请输入id'}]}]" />
        </a-form-item>
        <a-form-item
          label="分类目录"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-tree-select
            showSearch
            placeholder="选择分类目录"
            allowClear
            :treeData="treeData"
            treeDefaultExpandAll
            treeNodeFilterProp="title"
            v-decorator="['categoryId', {rules: [{required: true, message: '分类目录'}]}]"
          />
        </a-form-item>
        <a-form-item
          label="发表时间"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-date-picker
            :disabled="showable"
            style="width: 100%"
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            v-decorator="[
              'editTime',
              {rules: [{required: true, message: '请选择考试时间'}]}
            ]"></a-date-picker>
        </a-form-item>
        <a-form-item
          label="概要"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-textarea
            placeholder="请输入概要"
            :disabled="showable"
            v-decorator="['summary', {rules: [{required: true, message: '请输入概要'}, {validator: checkChineseNub}]}]"/>
        </a-form-item>
        <a-form-item
          label="描述"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-textarea
            placeholder="请输入描述"
            :disabled="showable"
            v-decorator="['metaDescription', {rules: [{required: true, message: '请输入描述'}, {validator: checkChineseNub}]}]"
          />
        </a-form-item>
      </a-form>
    </a-spin>
    <template slot="footer" >
      <div>
        <a-button key="cancel" @click="handleCancel">取消</a-button>
        <a-button key="forward" :loading="confirmLoading" type="primary" @click="handleOk">发布</a-button>
      </div>
    </template>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import moment from 'moment'
import { FormMixin } from '@/mixins/FormMixin'
import { treeList } from '@/api/cms/cmsCategory'
import { saveByPost, updateByPost } from '@/api/cms/cmsPost'
import { treeDataTranslate } from '@/utils/util'
export default {
  name: 'RecruitHrbAddOrUpdate',
  mixins: [FormMixin],
  data () {
    return {
      confirmLoading: false,
      treeData: [],
      parentSource: {},
      type: '',
      form: this.$form.createForm(this)
    }
  },
  mounted () {
    treeList().then(res => {
      this.treeData = treeDataTranslate(res.data, 'categoryId', 'name')
    })
  },
  methods: {
    edit (record, type) {
      this.visible = true
      this.type = type
      const { form: { setFieldsValue, resetFields } } = this
      if (record.editTime) {
        record.editTime = moment(record.editTime, 'YYYY-MM-DD HH:mm:ss')
      }
      if (['edit', 'show'].includes(type)) {
        this.confirmLoading = true
        this.$nextTick(() => {
          setFieldsValue(pick(record, ['id', 'categoryId', 'editTime', 'summary', 'metaDescription']))
        })
        this.confirmLoading = false
      } else {
        resetFields()
      }
    },
    // 获取父组件的数据
    getParentSource (dataSource) {
      this.parentSource = dataSource
    },
    handleOk () {
      this.$emit('parentSource')
      this.form.validateFields(async (err, values) => {
        if (!err) {
          this.confirmLoading = true
          try {
            if (this.type === 'add') {
              // 进行保存操作
              const post = this.parentSource
              // 状态为发布
              post.status = '1'
              post.categoryId = values.categoryId
              post.summary = values.summary
              post.metaDescription = values.metaDescription
              post.editTime = moment(values.editTime).format('YYYY-MM-DD HH:mm:ss')
              saveByPost(post).then(res => {
                this.$message.success('保存成功')
                this.$router.push({ name: 'postList' })
              }).catch(err => {
                this.$message.error(err.msg)
              })
            } else if (this.type === 'edit') {
              // 进行修改操作
              const post = this.parentSource
              // 状态为发布
              post.status = '1'
              post.categoryId = values.categoryId
              post.summary = values.summary
              post.metaDescription = values.metaDescription
              post.editTime = moment(values.editTime).format('YYYY-MM-DD HH:mm:ss')
              updateByPost(post).then(res => {
                this.$message.success('保存成功')
                this.$router.push({ name: 'postList' })
              }).catch(err => {
                this.$message.error(err.msg)
              })
            }
            setTimeout(() => {
              this.confirmLoading = false
              this.$emit('ok')
              this.handleCancel()
            }, 1500)
          } catch (e) {
            this.confirmLoading = false
            this.$message.error(e.msg)
          }
        }
      })
    },
    // 校验字数，少于30个字
    checkChineseNub (rule, value, callback) {
      var intLength = 0
      for (var i = 0; i < value.length; i++) {
        if ((value.charCodeAt(i) < 0) || (value.charCodeAt(i) > 255)) {
          intLength = intLength + 2
        } else {
          intLength = intLength + 1
        }
      }
      if (intLength <= 60) {
        callback()
      } else {
        callback(new Error('请输入小于30个汉字！'))
      }
    }
  }
}
</script>

<style scoped>

</style>
